package cn.ug.analyse.service.impl;

import cn.ug.analyse.bean.ChannelStaffBean;
import cn.ug.analyse.mapper.ChannelMapper;
import cn.ug.analyse.mapper.ChannelStaffMapper;
import cn.ug.analyse.mapper.entity.ChannelEntity;
import cn.ug.analyse.mapper.entity.ChannelStaffEntity;
import cn.ug.analyse.mapper.entity.QuerySubmit;
import cn.ug.analyse.service.ChannelStaffService;
import cn.ug.analyse.web.submit.ChannelStaffSubmit;
import cn.ug.bean.base.DataTable;
import cn.ug.bean.base.Page;
import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.SerializeObjectError;
import cn.ug.service.impl.BaseServiceImpl;
import cn.ug.util.ChannelNumberUtil;
import cn.ug.util.UF;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.dozer.DozerBeanMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 渠道管理
 *
 * @author zhaohg
 * @date 2018/08/06.
 */
@Service
public class ChannelStaffServiceImpl extends BaseServiceImpl implements ChannelStaffService {

    @Resource
    private ChannelMapper      channelMapper;
    @Resource
    private ChannelStaffMapper channelStaffMapper;
    @Resource
    private DozerBeanMapper    dozerBeanMapper;
    @Resource
    private RedisTemplate      redisTemplate;

    /**
     * 成员默认密码
     */
    private static final String STAFF_DEFAULT_PASSWORD = "UG945723";

    @Transactional
    @Override
    public SerializeObject insert(ChannelStaffSubmit submit) {
        submit.checkParams();
        ChannelEntity channel = channelMapper.findById(submit.getChannelId());
        if(channel != null) {
            ChannelStaffEntity staff = channelStaffMapper.getStaffByMobile(submit.getMobile());
            if(staff  != null)
                return new SerializeObjectError<>("210000024");

            ChannelStaffEntity entity = dozerBeanMapper.map(submit, ChannelStaffEntity.class);
            //获取成员最大编号
            String staffNumber = String.valueOf(channelStaffMapper.maxStaffNumber(channel.getId()));
            staffNumber = ChannelNumberUtil.getInstance().nextStaffNumber(staffNumber, channel.getNumber());
            entity.setNumber(staffNumber);
            entity.setPassword(DigestUtils.md5Hex(STAFF_DEFAULT_PASSWORD));
            entity.setInviteCode(UF.getRandomUUID()); // TODO 邀请码
            int success = channelStaffMapper.insert(entity);
            channelMapper.updateStaffCount(channel.getId());
            if (success > 0) {
                return new SerializeObject<>(ResultType.NORMAL, "00000001");
            }
        }
        return new SerializeObjectError<>("00000005");
    }

    @Override
    public SerializeObject updateStatus(ChannelStaffSubmit submit) {
        int success = channelStaffMapper.updateStaffStatusById(submit.getId(), submit.getIsEnable());
        if (success > 0) {
            return new SerializeObject<>(ResultType.NORMAL, "00000001");
        }
        return new SerializeObjectError<>("00000005");
    }

    @Override
    public SerializeObject resetPassword(Long id) {
        String password = DigestUtils.md5Hex(STAFF_DEFAULT_PASSWORD);
        channelStaffMapper.resetPassword(id, password);
        return new SerializeObjectError<>("00000001");
    }

    @Override
    public SerializeObject findById(Long id) {
        ChannelStaffEntity entity = channelStaffMapper.findById(id);
        if (entity != null) {
            ChannelStaffBean bean = dozerBeanMapper.map(entity, ChannelStaffBean.class);
            return new SerializeObject<>(ResultType.NORMAL, "00000001", bean);
        }
        return new SerializeObjectError("00000005");
    }

    @Override
    public SerializeObject findList(ChannelStaffSubmit submit) {
        QuerySubmit querySubmit = new QuerySubmit();
        submit.setParams(querySubmit);

        int count = channelStaffMapper.count(querySubmit);
        Page page = new Page(submit.getPageNum(), submit.getPageSize(), count);
        List<ChannelStaffBean> list = new ArrayList<>(count);
        this.query(querySubmit, count, list);

        return new SerializeObject<>(ResultType.NORMAL, "00000001", new DataTable<>(page, list));
    }

    @Override
    public List<ChannelStaffBean> findListByChannelId(Long channelId) {
        if (channelId > 0) {
            QuerySubmit querySubmit = new QuerySubmit();
            querySubmit.put("channelId", channelId);
            querySubmit.setLimit(null, null);

            int count = channelStaffMapper.count(querySubmit);
            List<ChannelStaffBean> list = new ArrayList<>(count);
            this.query(querySubmit, count, list);

            return list;
        }
        return null;
    }


    @Override
    public List<ChannelStaffBean> export(ChannelStaffSubmit submit) {
        QuerySubmit querySubmit = new QuerySubmit();
        querySubmit.put("channelId", submit.getChannelId());
        querySubmit.put("realName", submit.getRealName());
        querySubmit.put("mobile", submit.getMobile());
        querySubmit.setLimit(null, null);

        int count = channelStaffMapper.count(querySubmit);
        List<ChannelStaffBean> list = new ArrayList<>(count);
        this.query(querySubmit, count, list);
        return list;
    }

    private void query(QuerySubmit querySubmit, int count, List<ChannelStaffBean> list) {
        if (count > 0) {
            List<ChannelStaffEntity> channelList = channelStaffMapper.findList(querySubmit);
            Iterator<ChannelStaffEntity> iterator = channelList.iterator();
            while (iterator.hasNext()) {
                ChannelStaffBean bean = dozerBeanMapper.map(iterator.next(), ChannelStaffBean.class);
                list.add(bean);
            }
        }
    }

    @Override
    @Transactional
    public SerializeObject insertStaffByExcel(File destFile, Long channelId) {
        ChannelEntity entity = channelMapper.findById(channelId);
        if (entity == null) {
            return new SerializeObjectError("21000005");//渠道不存在
        }

        try {
            FileInputStream inputStream = new FileInputStream(destFile);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
            reader.readLine();//第一行信息，为标题信息，不用,如果需要，注释掉
            //获取成员最大编号
            String staffNumber = String.valueOf(channelStaffMapper.maxStaffNumber(entity.getId()));
//            int number = Integer.parseInt(staffNumber);

            String line = null;
            while ((line = reader.readLine()) != null) {
                String item[] = line.split(",");//CSV格式文件为逗号分隔符文件，这里根据逗号切分
                ChannelStaffEntity staff = new ChannelStaffEntity();
                staff.setChannelId(entity.getId());
                staff.setRealName(item[0]);
                staff.setMobile(item[1]);
                staff.setPassword(DigestUtils.md5Hex(STAFF_DEFAULT_PASSWORD));
//                number = number + 1;
//                staffNumber = String.valueOf(number);
                staffNumber = ChannelNumberUtil.getInstance().nextStaffNumber(staffNumber, entity.getNumber());
                if(StringUtils.isEmpty(staffNumber)){
                    return new SerializeObjectError("210000020");
                }
                staff.setNumber(staffNumber);
                staff.setInviteCode(UF.getRandomUUID());
                ChannelStaffEntity channelStaffEntity = channelStaffMapper.getStaffByMobile(staff.getMobile());
                if(channelStaffEntity  != null){
                    return new SerializeObjectError<>("210000024");
                }
                channelStaffMapper.insert(staff);
                channelMapper.updateStaffCount(entity.getId());
            }
            inputStream.close();
            reader.close();

            return new SerializeObject(ResultType.NORMAL, "00000001");

        } catch (Exception e) {
            getLog().error("import excel error.", e);
            return new SerializeObjectError("21000006");
        }
    }


}
